package com.cooper.controllers.item;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.ResourceConstants;
import com.cooper.controllers.Controller;
import com.cooper.controllers.LoginRequired;
import com.cooper.entity.LikeDetailEntity;
import com.cooper.entity.UserInfo;
import com.cooper.service.item.ItemStatService;
import com.cooper.service.item.LikeDetailService;
import com.cooper.service.seller.ShopStatService;
import com.cooper.util.Controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

@LoginRequired
public class StatisticsController extends Controller {
	
	@Autowired
	private ItemStatService itemStatService;

	@Autowired
	private ShopStatService shopStatService;
	
	@Autowired
	private LikeDetailService likeDetailService;

	@Get("like") @Post("like")
	public Object like(Invocation inv, @Param("itemId") Long itemId) throws Exception{
		UserInfo userInfo = Controllers.getUserInfo(inv);
		
		if(itemId!=null&&userInfo!=null){
			LikeDetailEntity detailEntity = this.likeDetailService.getEntityByUserId(ResourceConstants.LikeOrigin.ITEM_LIKE, itemId, userInfo.getId());
		    if(detailEntity!=null){
		    	if(detailEntity.getScore()==1){
		    		return this.shopStatService.unlike(detailEntity, userInfo,ResourceConstants.LikeOrigin.ITEM_LIKE);
		    	}else if(detailEntity.getScore()==-1){
		    		return this.shopStatService.like(detailEntity, userInfo,ResourceConstants.LikeOrigin.ITEM_LIKE);
		    	}
		    }else{
		    	LikeDetailEntity likeDetail = new LikeDetailEntity();
				likeDetail.setOuterId(itemId);
				likeDetail.setUserId(userInfo.getId());
				likeDetail.setClientIp(Controllers.getClientIp(inv));
				return this.shopStatService.like(likeDetail, userInfo,ResourceConstants.LikeOrigin.ITEM_LIKE);
		    }
		}
		
		return null;
	}
	
}
